leetcode刷题记录20

介绍

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:
Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16
The two words can be “abcw”, “xtfn”.

Example 2:
Given [“a”, “ab”, “abc”, “d”, “cd”, “bcd”, “abcd”]
Return 4
The two words can be “ab”, “cd”.

Example 3:
Given [“a”, “aa”, “aaa”, “aaaa”]
Return 0
No such pair of words.

思路

位操作 利用集合去重

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution(object):
def maxProduct(self, words):
"""
:type words: List[str]
:rtype: int
"""
wordlength=[len(i) for i in words]
l=len(words)
if l==0:
return 0
else:
r=0
wordlist=[list(set(i)) for i in words]
wordnumbers=[0 for i in range(l)]
for i in range(l):
numsum=0
for j in wordlist[i]:
numsum=numsum+2**(ord(j)-97)
wordnumbers[i]=numsum
for i in range(l):
if i==l-1:
return r
else:
for j in range(i+1,l):
if wordnumbers[i]^wordnumbers[j]==wordnumbers[i]+wordnumbers[j]:
r=max(wordlength[i]*wordlength[j],r)